from myhomework.account.daos import *
from myhomework.common.daos import *

def process_exception(func):
    def new_view(request,context={}):
        try:
            response = func(request,context)
        except Exception,e:
            return HttpResponse('{"error_type":"%s","error":"%s"}'%(type(e).__name__,e), mimetype="text/plain")
        return response
    return new_view

def require_perm(perm=''):
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            perm_processed=[]
            for perm_to_process in perm.split('.'):
                perm_in_request = get_param(request,perm_to_process)
                perm_processed.append(perm_in_request if not perm_in_request is None else perm_to_process)
            perm_processed = '.'.join(perm_processed)
            if(not PermissionDao.user_has_perm(request.user, perm_processed)):
                raise NoPermission(perm)
            return view_func(request, *args, **kwargs)
        return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
    return decorator

def need_settings(perm=''):
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            
            result = SettingDao.get_setting(perm)
            
            print 'result'
            print result
            
            if ( not result ):
                raise NoPermission(perm)
            
            return view_func(request, *args, **kwargs)
            
        return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
    return decorator